'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
import os
from zope.interface import Interface, Attribute
from dopplershift.collector.templates import ErrorTemplateNotFound
from dopplershift.core.containers.mediator import getMediator
import logging
from dopplershift.collector.resource import find_and_render
logger = logging.getLogger(__name__)

class IDSCollectorRenderer(Interface):
    default_content_type = Attribute("default content type")
    def render(self, data, data_type=None):
        '''
        rendering method, has return result of rendrering
        '''
    def redirect(self, redirect_url):
        '''
        redirecting method
        '''
    def error_render(self, error_code):
        '''
        render error message
        '''
    def prepare(self, data, calls_idents, as_string=True):
        '''
        preparation data dict for rendering
        '''
    def prepare_json_data(self, data, as_sring=True):
        '''
        internal method for preparing json data for current plugin format
        '''
    def prepare_xml_data(self, data, as_string=True):
        '''
        internal method for xml data preparation for current plugin format
        '''

class DefaultRenderer(object):
    name = 'default'
    application = 'collector.renderer'
    def configure(self, config):
        self._config = config
        self._default_schema_path = config.get_templates_path()
        self._prerendered_errors = {}
        self._internal_errors = {}
        self._templates = {}
        self._templates_path = config.get_templates_path()
        self.default_collector_renderer = config.get("default_collector_renderer")
        self._reload_template = config.get_reload_template()
        self._loadTemplates(config)
        self._default_headers =list(config.get_list('default', 'headers'))
        self.config = getMediator().get("AppConfig")
    def _checkRequestDebug(self, request):
        if self.config.get("PRODUCTION"): return False
        if 'debug' not in request.args:
            return False
        if '1' not in request.args['debug']:
            return False
        return True
    def loadFile(self, template_name, as_handler=False):
        d= None
        fname = os.path.join(self._default_schema_path, template_name)
        if os.path.isfile(fname):
            fh = open(fname)
            if as_handler == True: return fh
            d = fh.read()
            fh.close()
        return d
    def getTemplate(self, template_name):
        if template_name in self._templates:
            return self._templates[template_name]
        tmpl = self.loadFile(template_name)
        if tmpl is not None:
            self._templates[template_name] = tmpl
    def _loadTemplates(self, config):
        for template_name,renderer in config.get_templates_all():
            if renderer == None and self.name == self.default_collector_renderer:
                self.getTemplate(template_name)
            elif renderer == self.name:
                self.getTemplate(template_name)
        if self.default_collector_renderer != self.name:
            return
        for el in ['404', '403', '500']:
            tmpl_path = config.get_error_template_path(el)
            if tmpl_path is None:
                raise ErrorTemplateNotFound(el)
            if tmpl_path[1] != None:
                self._internal_errors[el] = tmpl_path[1].split('/')[1:]
                continue
            tmpl = self.getTemplate(tmpl_path[0])
            if  tmpl is None:
                raise ErrorTemplateNotFound(el)
            self._prerendered_errors[el] = tmpl
    def error(self, request, code):
        if str(code) in self._internal_errors:
            request.postpath = self._internal_errors[str(code)]
            res = find_and_render(request)
            
            return
        getMediator().get('ErrorRender').error_render(request, code)
    def render(self, request, response, template_name, content_type=None):
        self.headers(request)
        if self._checkRequestDebug(request): 
            return self.rendering(request, response, None, self.default_content_type)
        if content_type == None:
            content_type = 'text/html'            
        elif content_type ==  'ololo/xml':
            content_type = self.default_content_type
        self.rendering(request, response, template_name, content_type)
    def _session(self, request, session):
        if session is None:
            return
        for key, value in session.iteritems():
            if value != None:
                request.addCookie(key,value, path='/')
            else:
                request.addCookie(key,value, path='/')
    def headers(self, request):
        for key,value in self._default_headers:
            logger.debug('set request %s response header %s/%s'%(id(request), key,value))
            request.setHeader(key, value)
    def rendering(self, request, data, template_name, content_type):
        '''
        '''
    def prepare(self, data_dict, calls_idents, as_string=True, request=None):
        '''
        '''
        raise NotImplemented
